import java.io.Serializable;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Hashtable;
import java.rmi.server.UnicastRemoteObject;

 

public class Server extends UnicastRemoteObject implements Serializable,Server_itf {
	
	//attributs
	private static int port = 1099;
	private static String nom = "monserveur";
	
	//peut être static
	private static int id_object;//=0;
	//serveur de noms
	private static Hashtable<String,Integer> registres;// = new Hashtable();
	
	private static Hashtable<Integer,ServerObject> serverObjects;// = new Hashtable();
	

	 protected Server() throws RemoteException{
		 //this.port = 1099;
		 Server.registres = new Hashtable<String,Integer>();
		 Server.serverObjects = new Hashtable<Integer,ServerObject>();
		 Server.id_object=0;
	 }

	@Override
	public int lookup(String name) throws RemoteException{
		// TODO Auto-generated method stub
		System.out.println(registres.contains(name));
		if(registres.contains(name)){
			int id = registres.get(name);
			return id;
		}
		else{
			return 0;
		}
	}

	@Override
	public void register(String name, int id) throws RemoteException {
		// TODO Auto-generated method stub
		registres.put(name,id);
	}

	@Override
	public int create(Object o) throws RemoteException {
		// TODO Auto-generated method stub
		int i = this.id_object++;
		ServerObject so = new ServerObject(i,o);
		serverObjects.put(i,so);
		
		return 0;
	}

	@Override
	public Object lock_read(int id, Client_itf client) throws RemoteException {
		// TODO Auto-generated method stub
		if(serverObjects.contains(id)){
			ServerObject svo= serverObjects.get(id);
			return svo.lock_read(client);
		}
		else{
			return null;
		}
	}

	@Override
	public Object lock_write(int id, Client_itf client) throws RemoteException {
		// TODO Auto-generated method stub
		if(serverObjects.contains(id)){
			ServerObject svo= serverObjects.get(id);
			return svo.lock_write(client);
		}
		else{
			return null;
		}
	}
	
	//lancer le serveur
	public static void main(String args[]) {
		try {
			LocateRegistry.createRegistry(port);
			Server_itf server= new Server();
			Naming.rebind("//localhost:"+port+"/monserveur",server);
			
		} catch (RemoteException e) {
			System.out.println("erreur lancement Server1");
			e.printStackTrace();
		}catch (MalformedURLException e) {
			System.out.println("erreur lancement Server2");
			e.printStackTrace();
		}
		
		
	}

}
